// pages/movies/more-movie/more-movie.js
var app = getApp();
var utils = require('../../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    category: '',
    movies: {},
    requestUrl: '',
    totalCount: 0,
    isEmpty: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var category = options.category;
    this.setData({
      category: category
    })
    var dataUrl = '';
    switch (category) {
      case "正在热映":
        dataUrl = app.globalData.doubanBase + '/v2/movie/in_theaters';
        break;
      case "即将上映":
        dataUrl = app.globalData.doubanBase + '/v2/movie/coming_soon';
        break;
      case "豆瓣Top250":
        dataUrl = app.globalData.doubanBase + '/v2/movie/top250';
        break;
    }
    this.setData({
      requestUrl: dataUrl
    })
    utils.http(dataUrl, this.processDoubanData)
  },
  // 处理豆瓣数据
  processDoubanData: function (moviesDouban) {
    var movies = [];
    for (var idx in moviesDouban.subjects) {
      var subject = moviesDouban.subjects[idx];
      var title = subject.title;
      if (title.length >= 6) {
        title = title.substring(0, 6) + '...';
      }
      var temp = {
        stars: utils.convertToStarsArray(subject.rating.stars),
        title: title,
        average: subject.rating.average,
        converageUrl: subject.images.large,
        movieId: subject.id
      }
      movies.push(temp);
    }
    var totalMovies = {};

    // 如果要绑定新的护具，那么需要同旧有的数据，绑定在一起
    if (!this.data.isEmpty) {
      totalMovies = this.data.movies.concat(movies);
    } else {
      totalMovies = movies;
      this.setData({
        isEmpty: false
      })
    }

    this.setData({
      movies: totalMovies,
      totalCount: this.data.totalCount + 20
    });
    wx.stopPullDownRefresh();
  },
  // 设置标题栏，需要在onReady方法中，此方法被调用时，表示页面渲染完成了
  onReady: function (event) {
    var that = this;
    // 动态设置标题栏
    wx.setNavigationBarTitle({
      title: that.data.category,
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  onReachBottom: function () {
    console.log("加载更多")
    var nextUrl = this.data.requestUrl + "?start=" + this.data.totalCount + "&count=20";
    utils.http(nextUrl, this.processDoubanData);
  },
  onPullDownRefresh: function (event) {
    console.log("下拉刷新")
    this.setData({
      movies: {},
      isEmpty: true,
      totalCount: 0
    })
    var refreshUrl = this.data.requestUrl + "?star=0&count=20";
    utils.http(refreshUrl, this.processDoubanData)
  },  //跳转到电影详情
  onMovieTap: function (event) {
    var movieId = event.currentTarget.dataset.movieId;
    wx.navigateTo({
      url: '../movie-detail/movie-detail?id=' + movieId
    })
  }
})